import { clsx, getToUserPath } from "../common/utils";
import { useEffect, useRef } from "react";
import { Avatar, Button } from "antd";
import { GoodsModel } from "../common/model";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { Like } from "./Icon";
import { DefaultAvatar } from "../common/constant";
import { ResBody, request } from "../common/request";
import { useSystemStore } from "../store/system";

export const GoodsCard: React.FC<{
  data: GoodsModel;
  onDeleteClick?: (id: number) => void;
  showAction?: boolean; //是否展示下方操作面板
  onLikeSwitch?: (gid: number, liked_id: number | null) => void;
}> = ({ data, onDeleteClick, showAction, onLikeSwitch }) => {
  const [cover] = data.preview;
  const ref = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();
  const system = useSystemStore();
  const lo = useLocation();
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries, observer) => {
        entries?.forEach((entry) => {
          if (entry.isIntersecting) {
            // 目标元素进入视口
            // 在此处执行你的操作，比如加载图片、加载更多数据等
            const rootDom = entry.target as HTMLDivElement;
            rootDom.style.opacity = "1";

            //卸载订阅
            observer.disconnect();
          }
        });
      },
      { threshold: 0.1 }
    );

    // 监听目标元素
    observer.observe(ref.current!);
    return () => {
      observer.disconnect();
    };
  }, []);

  const onLikeClick = async () => {
    const ret = await request.post<any, ResBody>(
      `/api/relation/switch-like/${data.id}`
    );
    if (ret.code === 200) {
      system.message("success", ret.msg);
      onLikeSwitch?.(data.id, ret.like_id);
    }
  };

  return (
    <div
      className={clsx(
        "relative rounded-lg overflow-hidden shadow-lg",
        "opacity-0 transition-opacity duration-800 ease-in"
      )}
      ref={ref}
    >
      {cover && (
        <Link to={`/g/${data.id}`}>
          <img
            className="w-full object-cover"
            alt=""
            src={cover.url}
            loading="lazy"
            decoding="async"
          />
        </Link>
      )}
      <div className="px-2 py-2">
        <Link to={`/g/${data.id}`} className="text-lg block mb-2 font-bold">
          {data.title}
        </Link>
        <div
          className="flex items-center text-font2"
          onClick={(evt) => evt.stopPropagation()}
        >
          <Link to={getToUserPath(data.user?.account!, lo.pathname)}>
            <Avatar
              size={24}
              src={
                <img
                  src={data.user?.avatar ? data.user.avatar : DefaultAvatar}
                  alt=""
                  loading="lazy"
                  decoding="async"
                />
              }
            />
          </Link>
          <Link
            to={getToUserPath(data.user?.account!, lo.pathname)}
            className="text-sm ml-1"
          >
            {data.user?.nickname}
          </Link>
          <div className="flex-1" />
          <Like
            size={20}
            onClick={onLikeClick}
            liked={!!data.liked_id}
            className="hover:text-[#F44336] cursor-pointer"
          />
          {data.like_count > 0 && (
            <span onClick={onLikeClick} className="text-sm cursor-pointer">
              {data.like_count}
            </span>
          )}
        </div>
      </div>
      {showAction && (
        <>
          <div className="flex">
            <Button
              type="primary"
              className="!bg-lime-600 hover:opacity-90 w-1/2 rounded-none"
              onClick={() => {
                navigate(`/edit/${data.id}`);
              }}
            >
              编辑
            </Button>
            <Button
              type="primary"
              className="w-1/2 rounded-none"
              onClick={() => {
                onDeleteClick?.(data.id!);
              }}
            >
              删除
            </Button>
          </div>
        </>
      )}
    </div>
  );
};
